<template>
  <BasicModal
    v-bind="$attrs"
    v-model:visible="showContract"
    title="查看记录"
    width="95%"
    :showCancelBtn="false"
    :showOkBtn="false"
  >
    <div class="add_project">
      <a-button type="primary" @click="exportFn">导出</a-button>
    </div>
    <view v-for="(v, i) in dataSource" :key="i">
      <BasicTable
        :columns="getColumns(v.type)"
        :dataSource="[v]"
        bordered
        :pagination="false"
        :canResize="false"
        :showIndexColumn="false"
        :ref="(el) => getRef(el, i)"
        :rowSelection="{ type: 'checkbox' }"
        :customRow="customRow"
        :scroll="{ x: true }"
      >
        <template #contractResponseUrl="{ record }">
          <div
            v-if="record.contractResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'contractResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #designResponseUrl="{ record }">
          <div
            v-if="record.designResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'designResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #checkResponseUrl="{ record }">
          <div
            v-if="record.checkResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'checkResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #invoiceResponseUrl="{ record }">
          <div
            v-if="record.invoiceResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'invoiceResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>
        <template #tenderResponseUrl="{ record }">
          <div
            v-if="record.tenderResponse?.url"
            class="file_download"
            @click="fileDownloadFn(record, 'tenderResponse')"
            >附件下载</div
          >
          <div v-else>-</div>
        </template>

        <template #contractResponseAction="{ record }">
          <div class="action">
            <div @click="reviseRecord(record, 'hetong')">修改</div>
            <Popconfirm
              :title="`您确定要删除${record.projectName}的合同记录吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeRecord(record.contractResponse, 'hetong')"
            >
              <div class="del_class">删除</div>
            </Popconfirm>
          </div>
        </template>
        <template #designResponseAction="{ record }">
          <div class="action">
            <div @click="reviseRecord(record, 'chutu')">修改</div>
            <Popconfirm
              :title="`您确定要删除${record.projectName}的出图记录吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeRecord(record.designResponse, 'chutu')"
            >
              <div class="del_class">删除</div>
            </Popconfirm>
          </div>
        </template>
        <template #checkResponseAction="{ record }">
          <div class="action">
            <div @click="reviseRecord(record, 'yanshou')">修改</div>
            <Popconfirm
              :title="`您确定要删除${record.projectName}的验收记录吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeRecord(record.checkResponse, 'yanshou')"
            >
              <div class="del_class">删除</div>
            </Popconfirm>
          </div>
        </template>
        <template #invoiceResponseAction="{ record }">
          <div class="action">
            <div @click="reviseRecord(record, 'fapiao')">修改</div>
            <Popconfirm
              :title="`您确定要删除${record.projectName}的发票记录吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeRecord(record.invoiceResponse, 'fapiao')"
            >
              <div class="del_class">删除</div>
            </Popconfirm>
          </div>
        </template>
        <template #tenderResponseAction="{ record }">
          <div class="action">
            <div @click="reviseRecord(record, 'zhao')">修改</div>
            <Popconfirm
              :title="`您确定要删除${record.projectName}的招投标记录吗？`"
              ok-text="确定"
              cancel-text="取消"
              @confirm="removeRecord(record.tenderResponse, 'zhao')"
            >
              <div class="del_class">删除</div>
            </Popconfirm>
          </div>
        </template>
      </BasicTable>
    </view>
  </BasicModal>
  <ContractRecords ref="contract" @tableNeedUpdate="tableNeedUpdate" />
  <AcceptanceRecords ref="acceptance" @tableNeedUpdate="tableNeedUpdate" />
  <BiddingRecords ref="bidding" @tableNeedUpdate="tableNeedUpdate" />
  <DrawingRecord ref="brawing" @tableNeedUpdate="tableNeedUpdate" />
  <InvoiceRecord ref="invoice" @tableNeedUpdate="tableNeedUpdate" />
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message, Popconfirm } from 'ant-design-vue';
  import { useRoute } from 'vue-router';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { BasicModal } from '/@/components/Modal';
  import { queryAllLicense } from '/@/api/api';
  import ContractRecords from './ContractRecords.vue'; //合同记录
  import AcceptanceRecords from './AcceptanceRecords.vue'; //验收记录
  import BiddingRecords from './BiddingRecords.vue'; //招投标记录
  import DrawingRecord from './DrawingRecord.vue'; //出图记录
  import InvoiceRecord from './InvoiceRecord.vue'; //发票记录
  import {
    fileDownloadApi,
    logAllQueryApi,
    removeYanshou,
    removeHetong,
    removeZhaoTouBiao,
    removeChutu,
    removeFapiao,
  } from '/@/api/projectManagement';
  import { columns1, columns2, columns3, columns4, columns5 } from '../datas.ts';
  import * as XLSX from 'xlsx/xlsx.mjs';

  // const [registerTable] = useTable({
  //   columns: columns,
  //   bordered: true,
  //   actionColumn: {
  //     width: 250,
  //     title: 'Action',
  //     dataIndex: 'action',
  //     slots: { customRender: 'action' },
  //   },
  // });

  const acceptance = ref(); //验收
  const bidding = ref(); //招投标
  const brawing = ref(); //出图
  const invoice = ref(); //发票
  const contract = ref(); //合同
  const allLicense = ref([]);

  const reviseRecord = (res, kind) => {
    let data = {
      allLicense: allLicense.value,
      isEdit: true,
      editData: res,
      projectId: itemData.value.id,
    };
    if (kind == 'hetong') {
      if (!res.contractResponse) {
        return message.warn('暂无可修改选项');
      }
      contract.value.init(data);
    } else if (kind == 'chutu') {
      if (!res.designResponse) {
        return message.warn('暂无可修改选项');
      }
      brawing.value.init(data);
    } else if (kind == 'fapiao') {
      if (!res.invoiceResponse) {
        return message.warn('暂无可修改选项');
      }
      invoice.value.init(data);
    } else if (kind == 'zhao') {
      if (!res.tenderResponse) {
        return message.warn('暂无可修改选项');
      }
      bidding.value.init(data);
    } else if (kind == 'yanshou') {
      if (!res.checkResponse) {
        return message.warn('暂无可修改选项');
      }
      acceptance.value.init(data);
    }
  };

  const removeRecord = async (res, kind) => {
    let data = {
      id: res.id,
    };
    if (kind == 'hetong') {
      removeHetong(data).then(async () => {
        await getTableData();
        message.success('删除成功');
      });
    } else if (kind == 'chutu') {
      removeChutu(data).then(async () => {
        await getTableData();
        message.success('删除成功');
      });
    } else if (kind == 'fapiao') {
      removeFapiao(data).then(async () => {
        getTableData();
      });
    } else if (kind == 'zhao') {
      removeZhaoTouBiao(data).then(async () => {
        await getTableData();
        message.success('删除成功');
      });
    } else if (kind == 'yanshou') {
      removeYanshou(data).then(async () => {
        await getTableData();
        message.success('删除成功');
      });
    }
  };

  const itemData = ref({});
  const showContract = ref(false);

  const init = async (data) => {
    itemData.value = data;
    await getTableData();
    await getQueryAllLicense();
    showContract.value = true;
  };

  let getQueryAllLicense = () => {
    queryAllLicense().then((res) => {
      allLicense.value = res;
    });
  };

  defineExpose({
    init,
  });

  const dataSource = ref([]); //table数据
  const getTableData = () => {
    logAllQueryApi({
      projectId: itemData.value.id,
    }).then((res) => {
      dataSource.value = res || [];
    });
  };

  // 根据类型获取对应表格配置
  const getChildName = (type) => {
    let obj = {
      10: 'contractResponse',
      11: 'designResponse',
      12: 'checkResponse',
      13: 'invoiceResponse',
      14: 'tenderResponse',
    };
    return obj[type] || {};
  };

  const getRowColor = (record) => {
    let type = getChildName(record.type);
    let id = record[type].licenseCompanyId;
    if (!id) return '#fff';
    const license = allLicense.value.find((license) => license.id == id);
    console.log(license ? license.color : '#fff', 'license');
    return license ? license.color : '#fff';
  };

  const customRow = (record) => {
    return {
      // style: {
      //   background: getRowColor(record),
      // },
      class: 'asdant',
      onClick: () => {
        console.log('点击了');
      },
    };
  };

  //储存每一个ref
  const refList: any = ref([]);
  const getRef = (el, index) => {
    if (el) {
      refList.value[index] = el;
    }
  };

  // 根据类型获取对应表格配置
  const getColumns = (type) => {
    let obj = {
      10: columns1,
      11: columns2,
      12: columns3,
      13: columns4,
      14: columns5,
    };
    return obj[type] || {};
  };

  // 合同附件下载
  const fileDownloadFn = (record, key) => {
    let obj = {
      contractResponse: '合同记录',
      designResponse: '出图记录',
      checkResponse: '验收记录',
      invoiceResponse: '发票记录',
      tenderResponse: '招投标记录',
    };
    fileDownloadApi(`${record[key].url}`).then((res) => {
      console.log(res, '测试');
      download(res, `${record.projectName}${obj[key]}附件.${record[key].url.split('.')[1]}`);
    });
  };
  // blob下载
  const download = (blob, name) => {
    const link = document.createElement('a'); //创建一个a标签
    const url = window.URL.createObjectURL(blob); //将blob文件对象通过URL.createObjectURL()方法转为为url
    link.href = url; //为a标签设置href属性，并赋值为url
    link.download = name; //定义下载的文件名，文件名要包含后缀哟！如'导出EXCEL.xlsx'
    document.body.appendChild(link); //把a标签放在body上
    link.click(); //出发a标签点击下载
    document.body.removeChild(link); //在body中移除这个a标签
    URL.revokeObjectURL(url); //释放blob对象
  };

  // 导出
  const exportFn = () => {
    let selectRows: Array<Object> = [];
    refList.value.forEach((item) => {
      let keys: Array<Object> = item.getSelectRows();
      if (keys.length > 0) {
        selectRows.push(keys[0]);
      }
    });
    console.log('selectRows', selectRows);

    let obj = { 10: columns1, 11: columns2, 12: columns3, 13: columns4, 14: columns5 }; //数据类型对应的表格配置
    let dataKey = {
      10: 'contractResponse', //   合同数据key
      11: 'designResponse', //   出图记录数据key
      12: 'checkResponse', //   验收记录数据key
      13: 'invoiceResponse', //   发票记录数据key
      14: 'tenderResponse', //   招投标记录数据key
    };

    // xlsx数据
    const xlsxData: Array<Object> = [];
    // 处理选中数据
    selectRows.forEach((item) => {
      let columnNameList: Array<String> = []; //列名集合
      let columnDataList: Array<String> = []; //行数据
      for (let i = 0; i <= obj[item.type].length - 1; i++) {
        let v = obj[item.type][i];
        if (v.title != '操作' && v.dataIndex != 'url') {
          columnNameList.push(v.title);
          columnDataList.push(v.customRender({ record: item }));
        }
      }
      xlsxData.push(columnNameList);
      xlsxData.push(columnDataList);
      xlsxData.push([]);
      console.log('columnNameList', columnNameList);
      console.log('columnDataList', columnDataList);
    });

    // const data = [
    //   ['姓名', '年龄', '性别'],
    //   ['章三', '16', '男'],
    //   ['李四', '18', '男'],
    // ];
    // let data = dataSource.value.map((item) => {});

    let hetongData; //   合同
    let chutuData; //   出图记录
    let yanshouData; //   验收记录
    let fapiaoData; //   发票记录
    let tiaomuData; //   招投标记录

    // let mearges = [
    //   { s: { r: 0, c: 0 }, e: { r: 0, c: 8 } },
    //   { s: { r: 0, c: 9 }, e: { r: 0, c: 16 } },
    //   { s: { r: 0, c: 17 }, e: { r: 0, c: 24 } },
    //   { s: { r: 0, c: 25 }, e: { r: 0, c: 31 } },
    //   { s: { r: 0, c: 32 }, e: { r: 0, c: 43 } },
    // ];

    console.log(hetongData, 'hetongData');
    console.log(chutuData, 'chutuData');
    console.log(yanshouData, 'yanshouData');
    console.log(fapiaoData, 'fapiaoData');
    console.log(tiaomuData, 'tiaomuData');

    // let header = [
    //   '合同',
    //   ...new Array(8),
    //   '出图记录',
    //   ...new Array(7),
    //   '验收记录',
    //   ...new Array(7),
    //   '发票记录',
    //   ...new Array(6),
    //   '招投标记录',
    //   ...new Array(11),
    // ];
    // let hetongData = [
    //   '编号',
    //   '项目编号',
    //   '项目名称',
    //   '金额',
    //   '签订时间',
    //   '甲方',
    //   '资质公司编号',
    //   '资质公司名称',
    //   '添加时间',
    // ];
    // let chutuData = ['编号', '项目编号', '项目名称', '类型', '印章', '出图盖章时间', '数量', '添加时间'];
    // let yanshouData = ['编号', '项目编号', '项目名称', '类型', '盖章', '盖章时间', '数量', '添加时间'];
    // let fapiaoData = ['编号', '项目编号', '项目名称', '类型', '金额', '甲方', '添加时间'];
    // let tiaomuData = [
    //   '编号',
    //   '项目编号',
    //   '项目名称',
    //   '类型',
    //   '资质公司编号',
    //   '资质公司名称',
    //   '报名时间',
    //   '开标时间',
    //   '保证金',
    //   '标书类型',
    //   '备注',
    //   '添加时间',
    // ];

    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.aoa_to_sheet(xlsxData);

    worksheet['!cols'] = new Array(44).fill({
      wpx: 100,
    });
    console.log(worksheet['!cols']);

    // worksheet['!merges'] = merges;

    // let opt = dataSource.value.map((item) => {
    //   return {};
    // });

    XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet1');
    XLSX.writeFile(workbook, '增加记录.xlsx');
  };

  const tableNeedUpdate = () => {
    getTableData();
  };
</script>
<style lang="less" scoped>
  .add_project {
    button {
      margin-right: 10px;
    }
  }
  .action {
    > div,
    .del_class {
      color: #1990ff;
      cursor: pointer;
      margin: 5px 0;
    }
  }
  .file_download {
    cursor: pointer;
    color: rgba(0, 175, 233);
  }
</style>
